#include "DevMngSvr.h"
#include "proto_package.h"
#include "CmdId.h"
#include "proto_msg_handler.h"
uint64_t devid;
CDevMngSvr::CDevMngSvr(uv_loop_t* loop) :m_timer(loop)
{
	m_clientPtr=CTCPClient::NewTCPClien(loop);
	CMsgHandler* hlr = new CDevMngMsgHandler;
	m_msgHlrPtr = CMsgHandlerPtr(hlr);
	devid = 0x0100;
}


CDevMngSvr::~CDevMngSvr()
{
	LOG_INFO("~CDevMngSvr()");	
	m_clientPtr=nullptr;
}

void CDevMngSvr::StopSvr()
{
	m_clientPtr->CloseConn();
	m_timer.StopTimer();
}


void CDevMngSvr::StartRegister(std::string ip, uint16_t port)
{			
	m_clientPtr->OnConnStatus([=](CTCPClientPtr clt, int status){
		if (status == 0)
		{
			SBuf msg;			
			CProtoPackage::PackDevMngSvrRegisteMsg(m_moduleid, devid, &msg);
			devid++;
			clt->Write(msg.data(), msg.len());

			m_timer.StartTimer(0, 15 * 1000, [](void* usrData){
				CTCPClientPtr* cltPtr = (CTCPClientPtr*)usrData;
				SBuf msg;
				CProtoPackage::PackHeartbeatReqMsg(&msg);
				(*cltPtr)->Write(msg.data(), msg.len());
			}, (void*)&m_clientPtr);

			clt->OnMsgCall([=](SessionPtr session, char* szByte, int len){
				m_msgHlrPtr->HandleMsg(session, szByte, len);
			});
			clt->OnClose([=](SessionPtr session) {
				printf("client close\n");				
			});
		}
		
	});
	m_clientPtr->SetReConnInteral(5*1000);
	m_clientPtr->Connect((char*)ip.c_str(), port);
}
